<?php
/*
 *
 */
namespace Portal\Controller;
use Think\Controller\RestController;
/**
 * 首页
 */
class CrawlerController extends RestController{

    const CATEGORY_NEWS = 1;  //资讯

    const CATEGORY_VIDEO = 2;  //视频

    const KEY = 'Xiaowangzi@20161106';

    private $news_model;

    private $arr_msg = array(
        200 => 'Illegal token',
        201 => 'Method not allowed',
        202 => 'Param wrong',
        203 => 'Not allowed category type'
    );

    public function __construct()
    {
        parent::__construct();
        // 验证请求是否携带正确的Token值
        $token = trim(I('get.token'));
        if (!$token || $token != $this->get_current_token())
            $this->res_error(200, $this->get_current_token());
        $this->news_model = D('Portal/Posts');
        $this->anchor_model = D('Common/Anchor');
    }

    public function data_save(){
        switch($this->_method){
            case 'post':
                $this->_data_save();
                break;
            default:
                $this->res_error(201);
        }
    }

    public function anchor(){
        switch($this->_method){
            case 'get':
                $this->_anchor();
                break;
            default:
                $this->res_error(201);
        }
    }

    private function _anchor() {
        // 数据检查
        $type = I('get.type');
        $id = I('get.id');
        $res = None;
        if(empty($id))
            $this->res_error(202);
        if(empty($type))
            $type = self::CATEGORY_NEWS;
        switch ($type) {
            case self::CATEGORY_NEWS:
                $res = $this->anchor_model->get_anchor_info_by_id($id);
                break;
            default:
                $res = array();
        }
        $this->return_msg($res);
    }

    public function anchors(){
        switch($this->_method){
            case 'get':
                $this->_anchors();
                break;
            default:
                $this->res_error(201);
        }
    }

    private function _anchors() {
        // 数据检查
        $type = I('get.type');
        $res = None;
        if(empty($type))
            $type = self::CATEGORY_NEWS;
        switch ($type) {
            case self::CATEGORY_NEWS:
                $res = $this->anchor_model->get_all_anchor_info();
                break;
            default:
                $res = array();
        }
        $this->return_msg($res);
    }

    private function _news_data_save($arr = array()) {
        (empty($arr) || empty($arr['data'])) && $this->return_msg('', 'update size is 0');
        $size = count($arr['data']);
        $anchor = $arr['anchor'];
//        $anchor_platform = $anchor['platform'];
        $num = 0;
        //发布者暂停采集

        // 更新news对应数据
        foreach ($arr['data'] as $val) {
            $time = date('Y-m-d H:i:s');
            $title = $val['title'];
            $thumb = $val['thumb'];
            $catid = $val['catid'];
            $keywords = $val['keywords'];
            $description = $val['description'];
            $content = base64_decode($val['content']);
            $from = $val['from'];
            $search = $val['search'];
            $smeta = json_encode(array(
                'thumb' => $thumb,
                'template' => "artical"
            ));
            //检查是否重复
            $unid = md5($title);
            if($this->news_model->post_is_has($unid))
                continue;

            $data = array(
                'post_author' => '1',
                'title' => $title,
                'is_top' => 0,
                'recommended' => 0,
                'smeta' => $smeta,
                'unid' => $unid,
                'post_excerpt' => $description,
                'post_keywords' => $keywords,
                'post_status' => '0',
                'post_source' => $from,
                'post_date' => $time,
                'post_title' => $title,
                'post_content' => $content
            );
            $id = $this->news_model->data($data)->add();
            $num++;
            // Topic更新
            // 更新统计信息
        }
        // 更新anchor信息
        $this->anchor_model->where('id='.$anchor['id'])->save($anchor);
        $this->anchor_model->where('id='.$anchor['id'])->setInc('news_num', $num);

        $this->return_msg(array(
            'success' => $num,
            'failed' => ($size-$num),
            'reason' => 'news is repeat'
        ));

    }

    private function _video_data_save() {

    }

    private function _pics_data_save() {

    }

    //爬虫传递过来的数据进行处理并插入数据库
    private function _data_save(){
        $json_body = file_get_contents('php://input');
        $json_arr = json_decode( $json_body, true);
        $type = $json_arr['type'];
        if(empty($type))
            $type = self::CATEGORY_NEWS;
        switch ($type) {
            case self::CATEGORY_NEWS:
                $this->_news_data_save($json_arr);
                break;
            case self::CATEGORY_VIDEO:
                $this->_video_data_save($json_arr);
                break;
            case self::CATEGORY_PICS:
                $this->_pics_data_save($json_arr);
                break;
        }

        $this->res_error(203);
    }

    // token 生成方式sha1(unix时间戳前6位 + key)
    private function get_current_token() {
        return sha1(substr(time(), 0, 6) . self::KEY);
    }


    private function return_msg($data=array(), $msg = 'success'){
        $data = array(
            'errno' => 0,
            'data' => $data,
            'errmsg' => $msg
        );
        $this->response($data, 'json', 200);
    }

    private function res_error($err_code, $msg = '') {
        $data = array(
            'errno' => $err_code,
            'errmsg' => $this->arr_msg[$err_code] . ':' . $msg,
            'data' => array()
        );
        $this->response($data, 'json', 403);
    }


}


